package com.lry.basic.algorithm.common;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/9/7
 */
public class Rotate {
    public static void main(String[] args) {
//        int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
//        rotate(matrix);
//        print(matrix);
        int[][] matrix = new int[][]{{1,2,3},{4,5,6}};
        int[][] newMatrix = rotateMN(matrix);
        print(newMatrix);
    }

    public static void print(int[][] img){
        for(int i=0;i<img.length;i++){
            for(int j=0;j<img[0].length;j++){
                System.out.print(img[i][j]+" ");
            }
            System.out.println();
        }
    }
    //n*n矩阵顺时针旋转90°
    public static void rotate(int[][] matrix) {
        if(null==matrix||matrix.length==0)return;
        //转置
        for(int i=0;i<matrix.length;i++){
            for(int j=i;j<matrix.length;j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        //reverse每一行
        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix.length/2;j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][matrix.length-1-j];
                matrix[i][matrix.length-1-j] = temp;
            }
        }
    }
    //m*n矩阵顺时针旋转90°
    public static int[][] rotateMN(int[][] matrix){
        int m=matrix.length;//行
        int n=matrix[0].length;//列
        //新矩阵
        int [][] newMatrix = new int[n][m];
        //先转置
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                newMatrix[j][i] = matrix[i][j];
            }
        }
        //再reverse每一行
        for(int i=0;i<n;i++){
            for(int j=0;j<m/2;j++){
                int temp = newMatrix[i][j];
                newMatrix[i][j] = newMatrix[i][m-1-j];
                newMatrix[i][m-1-j] = temp;
            }
        }
        return newMatrix;
    }
}
